package com.formula.distribution.encrypt.advice;

import cn.hutool.core.io.IoUtil;
import com.formula.distribution.encrypt.encrypt.AbstractEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author:luyanan
 * @email:luyanan0718@163.com
 * @date 2018/12/15 11:56
 * @introduce
 **/
@Slf4j
public class DecryptHttpInputMessage implements HttpInputMessage {
    private HttpHeaders headers;


    private InputStream body;


    public DecryptHttpInputMessage(HttpInputMessage httpInputMessage, String key, String charset, AbstractEncrypt abstractEncrypt) throws Exception {

        this.headers = httpInputMessage.getHeaders();
        InputStream body = httpInputMessage.getBody();
        String content = IOUtils.toString(body, charset);

        String decryptBody = "";

//        content = "I5lVSQMX+7fcwkWshT85YKE+WnwsIccuUG/bRjyAgiA=";
        try {
            decryptBody = abstractEncrypt.decrypt(content, key);
        } catch (Exception e) {
            log.error("解密失败", e);
            decryptBody = content;
        }


        this.body = IOUtils.toInputStream(decryptBody, charset);
    }

    @Override
    public InputStream getBody() throws IOException {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
